package com.paomi.client.base;

import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.paomi.client.refresh.AdapterWrapper;
import com.paomi.client.refresh.SwipeToLoadHelper;
import com.paomi.client.view.LoadingDialog;
import com.paomi.client.widget.header.HeaderGetView;

import java.util.List;

import butterknife.ButterKnife;
import butterknife.Unbinder;
import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;

/**
 * Created by LS on 2017/5/27 0027.
 * 列表基类Fragment
 * 封装了LCE loading-content-empty 切换逻辑，以及下拉刷新和加载更多
 */

public abstract class BaseLCEFragment<M, P extends BaseLoadMorePresenter<BaseMvpLCEView>> extends BaseMvpFragment<BaseMvpLCEView, P> implements BaseMvpLCEView<M>,SwipeToLoadHelper.LoadMoreListener {
    private BaseGuideAdapter<M, BaseViewHolder> adapter;
    private PtrClassicFrameLayout ptrFrameLayout;
    private View mView;
    private Unbinder binder;
    private boolean isLoadMoreEnable = false;

    public AdapterWrapper getmAdapterWrapper() {
        return mAdapterWrapper;
    }
    public SwipeToLoadHelper getmLoadMoreHelper() {
        return mLoadMoreHelper;
    }

    private AdapterWrapper mAdapterWrapper;
    private SwipeToLoadHelper mLoadMoreHelper;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if(mView != null) return mView;
        View view = inflater.inflate(getFragmentLayoutId(), container, false);
        initArguments();
        return view;
    }

    /** 初始化Arguments*/
    protected void initArguments() {

    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if(binder == null) binder = ButterKnife.bind(this, view);
        if(mView != null)return;
        mView = view;
//        binder = ButterKnife.bind(this, view);
        initAdapter();
        initEvent();
    }
    public BaseGuideAdapter<M, BaseViewHolder> getAdapter() {
        return adapter;
    }

    protected void initEvent() {}

    @NonNull
    protected abstract int getFragmentLayoutId();

    /**
     * 如果有下拉刷新，需要调用{@link #setPtrFrameLayout(PtrClassicFrameLayout)}
     * @return
     */
    @NonNull
    protected abstract RecyclerView createRecycler();

    /** 是否允许加载更多
     * Note: Call after {@link #adapter} init, {@link #initAdapter()}*/
    protected void setLoadMoreEnable(boolean isLoadMoreEnable) {
        this.isLoadMoreEnable = isLoadMoreEnable;
    }

    /** 是否显示LoadMoreEnd布局
     * Note: Call after {@link #adapter} init, {@link #initAdapter()}*/
    public void setShowLoadMoreEnd(boolean isShowLoadMore) {
        if(adapter != null) adapter.setShowLoadMoreEnd(isShowLoadMore);
    }

    protected void initAdapter() {
        adapter = new BaseGuideAdapter<M, BaseViewHolder>(getItemLayout()) {
            @Override
            public void initEmpty(TextView empty) {
                BaseLCEFragment.this.initEmpty(empty);
            }

            @Override
            protected void convert(BaseViewHolder helper, M item) {
                BaseLCEFragment.this.convert(helper, item);
            }
        };
        RecyclerView mRecycler = createRecycler();
        if(mRecycler!=null){
            mRecycler.setLayoutManager(new LinearLayoutManager(getActivity()));

            adapter.bindToRecyclerView(mRecycler);
            mAdapterWrapper = new AdapterWrapper(adapter);
            mLoadMoreHelper = new SwipeToLoadHelper(mRecycler, mAdapterWrapper);
            mLoadMoreHelper.setLoadMoreListener(this);

            mRecycler.setAdapter(mAdapterWrapper);
//            mRecycler.addOnScrollListener(new RecyclerView.OnScrollListener() {
//                @Override
//                public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
//                    super.onScrollStateChanged(recyclerView, newState);
//                    //监听滑动
//                    isLoadMoreEnable=true;
//                }
//
//                @Override
//                public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
//                    super.onScrolled(recyclerView, dx, dy);
//                }
//            });
//            if(isLoadMoreEnable)adapter.setLoadMoreListener(new BaseGuideAdapter.OnLoadMoreListener() {
//                @Override
//                public void onLoadMoreRequested() {
//                    loadData(true);
//                }
//            }, mRecycler);
            adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(BaseQuickAdapter a, View view, int position) {
                    BaseLCEFragment.this.onItemClick(view,adapter.getItem(position));
                }
            });
            adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
                @Override
                public void onItemChildClick(BaseQuickAdapter a, View view, int position) {
                    BaseLCEFragment.this.onItemChildClick(view,adapter.getItem(position));
                }
            });
        }
//        adapter.addHeaderView()

        if (ptrFrameLayout != null) {
            HeaderGetView header=new HeaderGetView(getActivity());
            ptrFrameLayout.setHeaderView(header);
            ptrFrameLayout.addPtrUIHandler(header);
            ptrFrameLayout.setLastUpdateTimeRelateObject(this);
            ptrFrameLayout.setPtrHandler(new PtrDefaultHandler() {
                @Override
                public void onRefreshBegin(PtrFrameLayout frame) {
                    loadData(true);
                }

                @Override
                public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                    return super.checkCanDoRefresh(frame, content, header);   // 是否需要支持下拉刷新
                }
            });
        } else {
            loadData(true);
        }
    }

    protected void onItemChildClick(View view, M item) {}

    protected abstract int getItemLayout();

    protected abstract void initEmpty(TextView empty);

    protected abstract void convert(BaseViewHolder helper, M item);

    protected abstract void onItemClick(View view, M item);

    @Override
    public void loadData(boolean pullToRefresh) {
        getPresenter().loadData(pullToRefresh);
    }

    @Override
    public void setData(List<M> data, boolean pullToRefresh) {
        LoadingDialog.get().hideLoading();
        if(pullToRefresh && ptrFrameLayout != null) ptrFrameLayout.refreshComplete();
        adapter.setDatas(data);
    }

    protected void setPtrFrameLayout(PtrClassicFrameLayout ptrFrameLayout) {
        this.ptrFrameLayout = ptrFrameLayout;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if(binder != null) {
            binder.unbind();
            binder = null;
        }
    }

    public void getIntent(Class cl) {
        Intent intent = new Intent();
        intent.setClass(getActivity(), cl);
        startActivity(intent);
    }

    @Override
    public void onLoad() {

    }

    /**
     * 判断是否有网
     * @return
     */
    public int getNetworkType() {
        int netType = 0;
        ConnectivityManager connectivityManager = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        if (networkInfo == null) {
            return netType;
        }
        int nType = networkInfo.getType();
        if (nType == ConnectivityManager.TYPE_MOBILE) {
            netType = 1;
        } else if (nType == ConnectivityManager.TYPE_WIFI) {
            netType = 2;
        }
        return netType;
    }
}
